﻿//
// Created by xqyr on 2024/6/19.
//

#include "Mmqtt.h"
#include <QRandomGenerator>
#include <QDebug>
#include <QTime>
using QMQTT::Client;
Mmqtt::Mmqtt(const QString& ip, const uint port, QObject *parent)
: QObject(parent){
    client.reset(new Client(QHostAddress(ip),(int)port,this));
    connect(client.data(), &Client::connected, this, [&](){
        qDebug()<<"链接成功";
        status = connected;
        emit statusChanged(status);
    });
    connect(client.data(), &Client::disconnected, this,[&](){
        status = disconnected;
        emit statusChanged(status);
    });
    connect(client.data(), &Client::subscribed, this, &Mmqtt::subscribed);
    connect(client.data(), &Client::received, this, &Mmqtt::received);

    connect(client.data(),&Client::error,this,[](const QMQTT::ClientError error){
        qDebug()<<error;
    });

}

bool Mmqtt::connectMqtt(const QString& ip, uint port) {

    QString clientID;
    if(ip.isEmpty()) {
        clientID = "XYD-CXX"+QString::number(QRandomGenerator::global()->bounded(
                QTime::currentTime().toString("hhmmzzz").toInt()
                )); //合成 mqtt id
                qDebug()<<clientID;
        client->setClientId(clientID);
        client->setUsername("xiong");

       client->setCleanSession(true);
        client->setKeepAlive(60);
        client->connectToHost(); //连接mqtt
        qDebug()<<"链接开始";
    }
    return false;
}

bool Mmqtt::subscribe(const QString& topic, const int id) {
    qDebug()<<"订阅";
        client->subscribe(topic,id);

    return false;
}

bool Mmqtt::publish(const QMQTT::Message &mes) {
    client->publish(mes);
    return false;
}
